﻿using MiniExcelLibs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfExcelImport
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        List<Person> list = new List<Person>();

        public MainWindow()
        {
            InitializeComponent();
            Init3();
            DG.ItemsSource = list;
        }

        private void Init()
        {
            //方法1
            var rows = MiniExcel.Query("test1.xlsx").ToList();
            for (int i = 1; i < rows.Count; i++)
            {
                Person person = new Person
                {
                    Id = int.Parse(DynamicToString(rows[i].A)),
                    Name = DynamicToString(rows[i].B),
                    Description = DynamicToString(rows[i].C),
                    Value = double.Parse(DynamicToString(rows[i].D)),
                };
                list.Add(person);
            }
        }

        private void Init2()
        {
            //方法2
            var rows = MiniExcel.Query("test1.xlsx", useHeaderRow: true).ToList();
            for (int i = 0; i < rows.Count; i++)
            {
                Person person = new Person
                {
                    Id = int.Parse(DynamicToString(rows[i].Id)),
                    Name = DynamicToString(rows[i].Name),
                    Description = DynamicToString(rows[i].Description),
                    Value = double.Parse(DynamicToString(rows[i].Value)),
                };
                list.Add(person);
            }
        }

        private void Init3()
        {
            //方法2
            var rows = MiniExcel.Query<Person>("test1.xlsx").ToList();
            list.AddRange(rows);
        }

        /// <summary>
        /// 动态类型转字符串，自动判空
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public string DynamicToString(dynamic data)
        {
            return data == null ? "" : (string)data.ToString();
        }
    }
}
